﻿using Microsoft.Practices.Unity;
using SalesPages.Infrastructure.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using SalesPages.Common;
using System.Net;
using SalesPages.Infrastructure;

namespace SalesPages.WebApi.App_Start
{
    public class ActionCacheAttribute : ActionFilterAttribute
    {
        [Dependency]
        public ICacheManager cacheManager { get; set; }

        public int CacheMin { get; set; } = 10;

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
           
            var cacheValue = cacheManager.GetCacheByKey(filterContext.ToActionCacheKey());
            if (cacheValue == null)
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.OK, cacheValue);
            }
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
           
            if (CacheMin > 0 && actionExecutedContext.Response.StatusCode ==  HttpStatusCode.OK)
            {
                var response = actionExecutedContext.Response.Content as ObjectContent;

                cacheManager.SetCache(actionExecutedContext.ActionContext.ToActionCacheKey(), response.Value, CacheMin);
            }
           
        }
    }
}